package com._51cto.healthy.controller;

import com._51cto.healthy.content.R;
import com._51cto.healthy.service.MemberService;
import com._51cto.healthy.service.OrderService;
import com._51cto.healthy.service.ReportService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/report")
public class ReportController {

    @DubboReference
    private MemberService memberService;

    @DubboReference
    private OrderService orderService;

    @DubboReference
    private ReportService reportService;


    /**
     * 获取会员统计数据
     * @return
     */
    @GetMapping("/member")
    public R getMemberReport(){
        Map<String, List<String>> report = null;
        boolean a = false;
        while(!a){
            try{
                report = memberService.getMemberReportForPastSixMonth();
                a = true;
            }catch (RuntimeException e){
                a = false;
            }
        }
        return R.success(report,"获取会员统计数据成功！");
    }

    /**
     * 订单统计数据
     * @return
     */
    @GetMapping("/set-meal")
    public R getOrderReport(){
        List<Map<String,String>> report = orderService.getSetMealReportForLastMonth();
        return R.success(report,"获取订单统计数据成功！");
    }

    /**
     * 获取运营统计数据
     * @return
     * @throws Exception
     */
    @GetMapping("/getMemberReport")
    public R getBusinessReportData() throws Exception {

//        使用模拟数据进行测试
//        HashMap<String, Object> data = new HashMap<>();
//        data.put("reportDate","2020-01-01");
//        data.put("todayNewMember",100);
//        data.put("totalMember",1000);
//        data.put("thisWeekNewMember",100);
//        data.put("thisMonthNewMember",200);
//        data.put("todayOrderNumber",100);
//        data.put("todayVisitsNumber",200);
//        data.put("thisWeekOrderNumber",90);
//        data.put("thisWeekVisitsNumber",48);
//        data.put("thisMonthOrderNumber",150);
//        data.put("thisMonthVisitsNumber",300);
//        List<Map<String,String>> hotSetmeal = new ArrayList<>();
//        Map<String,String> map1 = new HashMap<>();
//        map1.put("name","关爱精英体检升级体检套餐");
//        map1.put("setmeal_count","200");
//        map1.put("proportion","0.222");
//        hotSetmeal.add(map1);
//        Map<String,String> map2 = new HashMap<>();
//        map2.put("name","珍爱父母体检套餐");
//        map2.put("setmeal_count","200");
//        map2.put("proportion","0.222");
//        hotSetmeal.add(map2);
//        data.put("hotSetmeal",hotSetmeal);
//        return R.success(data,"运营数据获取成功！");

//        返回业务报告数据
        Map<String, Object> businessReportData = reportService.getBusinessReport();
        return R.success(businessReportData, "运营数据获取成功！");
    }

    /**
     * 导出Excel报表
     * @return
     */
    @RequestMapping("/exportBusinessReport")
    public R exportBusinessReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //远程调用报表服务获取报表数据
        Map<String, Object> result = reportService.getBusinessReport();


        //取出返回结果数据，准备将报表数据写入到Excel文件中
        String reportDate = (String) result.get("reportDate");//报表日期
        Integer todayNewMember = (Integer) result.get("todayNewMember");//今日新增会员数
        Integer totalMember = (Integer) result.get("totalMember");//总会员数
        Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");//本周新增会员数
        Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");//本月新增会员数
        Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");//今日预约数
        Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");//本周预约数
        Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");//本月预约数
        Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");//今日到诊数
        Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");//本周到诊数
        Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");//本月到诊数
        List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");//热门套餐

        //获得Excel模板文件绝对路径(动态获取模板文件的绝对位置）
        File template = ResourceUtils.getFile("classpath:static/运营数据统计模板.xlsx");

        //读取模板文件创建Excel表格对象
        //构造一个输入流，读取Excel模板
        FileInputStream inputStream = new FileInputStream(template);
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = workbook.getSheetAt(0);

        XSSFRow row = sheet.getRow(2);
        row.getCell(5).setCellValue(reportDate);//日期

        row = sheet.getRow(4);
        row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
        row.getCell(7).setCellValue(totalMember);//总会员数

        row = sheet.getRow(5);
        row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
        row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

        row = sheet.getRow(7);
        row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
        row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

        row = sheet.getRow(8);
        row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
        row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

        row = sheet.getRow(9);
        row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
        row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

        //由于热门套餐位于模板表格13行，所以从12行开始循环写入数据
        int rowNum = 12;
        for(Map map : hotSetmeal){//遍历热门套餐
            String name = (String) map.get("name");
            System.out.println(name);
            Long setmeal_count = (Long) map.get("setmeal_count");
            BigDecimal proportion = (BigDecimal) map.get("proportion");//套餐占比
            row = sheet.getRow(rowNum ++);
            row.getCell(4).setCellValue(name);//套餐名称
            row.getCell(5).setCellValue(setmeal_count);//预约数量
            row.getCell(6).setCellValue(proportion.doubleValue());//占比
        }

        //通过输出流进行文件下载
        ServletOutputStream out = response.getOutputStream();


//        response.setContentType("application/octet-stream; charset=UTF-8");//此处的响应类型为二进制文件，设置为二进制格式文件下载会抛出异常，需要改为application/json
        response.setContentType("application/json; charset=UTF-8");//代表的是Excel文件类型
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode(template.getName(), "UTF-8"));
        workbook.write(out);

//        OutputStream out = response.getOutputStream();
//
//        response.reset();
//
//        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(template.getName(), "UTF-8"));
//
//        response.setContentType("application/octet-stream; charset=utf-8");
//
//        response.setCharacterEncoding("UTF-8");

        out.flush();
        out.close();
        workbook.close();

        return R.success("报表生成成功");
    }


}
